package Redis.StringRedisTemplate;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisUtil {
	
	@Autowired
	private  StringRedisTemplate stringRedisTemplate;
	
	public AtomicInteger num = new AtomicInteger(0);

	/*
	 * 实现乐观锁，乐观锁是依据redis事务实现的
	 */
    public Object testRedisOptismLock(String value) {

        try {
        	stringRedisTemplate.watch("OptismLock"); // 1
        	stringRedisTemplate.multi();
        	stringRedisTemplate.boundValueOps("OptismLock").set(value);
        	
        	TimeUnit.SECONDS.sleep(4);
        	
        	List<Object> list= stringRedisTemplate.exec();
        	System.out.println(list);
        	if(list != null&&!list.isEmpty() ){
        	    //操作成功
        	    System.out.println(value+"值设置成功");
        	}else{
        	    //操作失败
        	    System.out.println(value+"值设置失败");
        	}
        } catch (Exception e) {
            e.printStackTrace();
        }

        //自增
        num.incrementAndGet();
        
        return null;
    }
    
    /*
     * 实现并测试Redis事务
     */
    public void testTransaction() {
    	stringRedisTemplate.setEnableTransactionSupport(true);
        try {
            stringRedisTemplate.multi();//开启事务
            stringRedisTemplate.opsForValue().increment("transaction", 1);
            
            if(true)
            throw new Exception();
            
            stringRedisTemplate.opsForValue().increment("transaction2", 2);
            //提交
            stringRedisTemplate.exec();
        }catch (Exception e){
            System.out.println("redis事务回滚了");
            //开启回滚
            stringRedisTemplate.discard();
        }
    }
    
    
    public Runnable getTask(String value) {
    	
    	return new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				testRedisOptismLock(value);
				
			}
		};
    	
    }


	public void setEnableTransactionSupport(boolean b) {
		// TODO Auto-generated method stub
		 // 开启事务支持，在同一个 Connection 中执行命令
		  stringRedisTemplate.setEnableTransactionSupport(b);
	}
	
}
